package com.antdesignbackend.backend.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.antdesignbackend.backend.common.CalendarDate;
import com.antdesignbackend.backend.common.IpUtil;
import com.antdesignbackend.backend.common.http.HttpClientResult;
import com.antdesignbackend.backend.common.http.HttpClientUtils;
import com.antdesignbackend.backend.common.http.RequestType;
import com.antdesignbackend.backend.config.WebConfig;
import com.antdesignbackend.backend.common.returnResult.ReturnCode;
import com.antdesignbackend.backend.config.WxPayAppConfig;
import com.antdesignbackend.backend.entity.*;
import com.antdesignbackend.backend.entity.Collection;
import com.antdesignbackend.backend.entity.entityVo.*;
import com.antdesignbackend.backend.common.returnResult.ReturnVO;
import com.antdesignbackend.backend.service.*;
import com.antdesignbackend.backend.util.HttpRequest;
import com.antdesignbackend.backend.util.LatLonUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderRequest;
import com.github.binarywang.wxpay.bean.result.WxPayUnifiedOrderResult;
import com.github.binarywang.wxpay.constant.WxPayConstants;
import com.github.binarywang.wxpay.service.WxPayService;
import com.github.wxpay.sdk.WXPayUtil;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 公众号接口
 */
@Controller
@RequestMapping("/Applet")
public class AppletController {
    private Logger log = LoggerFactory.getLogger(this.getClass());
    private String openid;
    private Integer cId = null;

    SimpleDateFormat formattime = new SimpleDateFormat("yyyyMMddHHmmss");
    SimpleDateFormat formatdata = new SimpleDateFormat("yyyy-MM-dd");

    private WxPayService wxPayService;

    @Autowired
    AppletShopService appletShopService;

    @Autowired
    IShopService shopService;

    @Autowired
    AppletRoomService appletRoomService;

    @Autowired
    IImagesService imagesService;

    @Autowired
    IAppointmentService appointmentService;

    @Autowired
    CollectionService collectionService;

    @Autowired
    MemberService memberService;

    @Autowired
    RotationService rotationService;
    @Autowired
    MiddlecommandService middlecommandService;

    @Autowired
    UserRolesService userRolesService;

    @Autowired
    UserService userService;

    @Autowired
    WxPayAppConfig wxPayAppConfig;

    @Autowired
    OrderService orderService;

    @Autowired
    CabinetitemService cabinetitemService;

    @Autowired
    IRoomService roomService;

    @Autowired
    RolesService rolesService;

    @Autowired
    JoinInService joinInService;

    @Autowired
    AboutUsService aboutUsService;

    @Autowired
    CommonProblemService commonProblemService;

    @Autowired
    ChargingFlowService chargingFlowService;

    /**
     * 1. 获取优选门店接口
     * @param cityId 城市编号
     * @param countyId 区县编号
     * @param longitude 经度
     * @param latitude 纬度
     * @param pageNo 起始页
     * @param pageSize 每页条数
     * @param shopName 门店名称
     * @return
     */
    @GetMapping("/getPreferredSpaces")
    @ResponseBody
    public ReturnVO getPreferredSpaces(@RequestParam(value = "cityId",required = false) String cityId,
                                                 @RequestParam(value = "countyId",required = false) String countyId,
                                                 @RequestParam(value = "longitude",required = false) Double longitude,
                                                 @RequestParam(value = "latitude",required = false) Double latitude,
                                                 @RequestParam(value = "pageNo",required = false) Integer pageNo,
                                                 @RequestParam(value = "pageSize",required = false) Integer pageSize,
                                                 @RequestParam(value = "shopName",required = false) String shopName){
        ReturnVO returnVO = new ReturnVO();
        List<AppletShopVo> appletShopVoList = new ArrayList<>();
        try {
            QueryWrapper<AppletShopVo> queryWrapper = new QueryWrapper<>();
            if (cityId != null && !"".equals(cityId)){
                queryWrapper.eq("cityId",cityId);
            }
            if (countyId != null && !"".equals(countyId)){
                queryWrapper.eq("countyId",countyId);
            }
            if (shopName != null && !"".equals(shopName)){
                queryWrapper.like("shopName",shopName);
            }
            //计算总数
            int total = appletShopService.count(queryWrapper);
            if (total > 0){ //查询区数据
                appletShopVoList=appletShopService.getShopView(queryWrapper,new Page<>(pageNo,pageSize));
                if (appletShopVoList.size() > 0){
                    for (AppletShopVo shop:appletShopVoList){
                        //计算两点间的距离
                        if (longitude != null && latitude != null && shop.getLongitude() != null && shop.getLatitude() != null){
                            double distance = LatLonUtil.getDistance(longitude,latitude,shop.getLongitude(),shop.getLatitude());
                            shop.setDistance(distance/1000); //换算成公里
                        }
                        //拼接图片网络路径
                        if (shop.getImageUrl() != null && !shop.getImageUrl().equals("")){
                            shop.setImageUrl(WebConfig.host+"images/"+shop.getImageUrl());
                        }
                    }
                    //根据距离排序，距离升序 空值放最末
                    appletShopVoList = appletShopVoList.stream().sorted(Comparator.comparing(AppletShopVo::getDistance,Comparator.nullsLast(Double::compareTo))).collect(Collectors.toList());
                }
                returnVO.setTotal(total);
                returnVO.setData(appletShopVoList);
                returnVO.setExistence(1);
            }else { //查询城市数据
                QueryWrapper<AppletShopVo> cityWrap = new QueryWrapper<>();
                if (cityId != null && !"".equals(cityId)){
                    cityWrap.eq("cityId",cityId);
                }
                if (shopName != null && !"".equals(shopName)){
                    cityWrap.like("shopName",shopName);
                }
                //计算总数
                int total1 = appletShopService.count(cityWrap);
                if (total1 > 0){
                    appletShopVoList=appletShopService.getShopView(cityWrap,new Page<>(pageNo,pageSize));
                    if (appletShopVoList.size() > 0){
                        for (AppletShopVo shop:appletShopVoList){
                            //计算两点间的距离
                            if (longitude != null && latitude != null && shop.getLongitude() != null && shop.getLatitude() != null){
                                double distance = LatLonUtil.getDistance(longitude,latitude,shop.getLongitude(),shop.getLatitude());
                                shop.setDistance(distance/1000); //换算成公里
                            }
                            //拼接图片网络路径
                            if (shop.getImageUrl() != null && !shop.getImageUrl().equals("")){
                                shop.setImageUrl(WebConfig.host+"images/"+shop.getImageUrl());
                            }
                        }
                        //根据距离排序，距离升序 空值放最末
                        appletShopVoList = appletShopVoList.stream().sorted(Comparator.comparing(AppletShopVo::getDistance,Comparator.nullsLast(Double::compareTo))).collect(Collectors.toList());
                    }
                }
                returnVO.setTotal(total1);
                returnVO.setData(appletShopVoList);
                returnVO.setExistence(0);
            }
        }catch (Exception e){
            returnVO = new ReturnVO(ReturnCode.FAIL);
            log.error(e.getMessage());
        }
        return returnVO;
    }

    /**
     * 地图找店
     * @param cityId 城市id
     * @param longitude 经度
     * @param latitude 纬度
     * @param spaceType 空间类型
     * @param distance 距离 （米）
     * @return
     */
    @GetMapping("/getMapSpaces")
    @ResponseBody
    public List<AppletShopVo> getMapSpaces(@RequestParam(value = "cityId",required = false) String cityId,
                                        @RequestParam(value = "longitude",required = false) Double longitude,
                                        @RequestParam(value = "latitude",required = false) Double latitude,
                                        @RequestParam(value = "spaceType",required = false) String spaceType,
                                        @RequestParam(value = "distance",required = false) Double distance
                                        ){
        List<AppletShopVo> list = new ArrayList<>();
        try {
            //获得当前城市所有的数据
            QueryWrapper<AppletShopVo> queryWrapper = new QueryWrapper<>();
            if (cityId != null && !"".equals(cityId)){
                queryWrapper.eq("cityId",cityId);
            }
            if (spaceType != null && !"".equals(spaceType)){
                queryWrapper.eq("spaceType",spaceType);
            }
            if (appletShopService.count(queryWrapper) > 0){
                list = appletShopService.getShopView(queryWrapper,new Page<>(1,99999));
                Iterator<AppletShopVo> it =list.iterator();
                while (it.hasNext())
                {
                    AppletShopVo shop = it.next();
                    //计算两点间的距离
                    if (longitude !=null && latitude != null &&shop.getLongitude() != null && shop.getLatitude() != null){
                        Double distance1 = LatLonUtil.getDistance(longitude,latitude,shop.getLongitude(),shop.getLatitude());
                        //根据距离判断是否在指定范围
                        shop.setDistance(distance1/1000); //转换成公里
                        if (distance != null && distance != 0){
                            if(distance < distance1){ //移除指定范围外的数据
                                it.remove();
                            }
                        }
                    }else {
                        it.remove();
                    }
                }
            }
            if (list.size() > 0){
                for (AppletShopVo shop:list){
                    //拼接图片网络路径
                    if (shop.getImageUrl() != null && !shop.getImageUrl().equals("")){
                        shop.setImageUrl(WebConfig.host+"images/"+shop.getImageUrl());
                    }
                    //计算两点间的距离
                    if (longitude !=null && latitude != null &&shop.getLongitude() != null && shop.getLatitude() != null){
                        Double distance1 = LatLonUtil.getDistance(longitude,latitude,shop.getLongitude(),shop.getLatitude());
                        shop.setDistance(distance1/1000); //转换成公里
                    }
                }
                //根据距离排序，距离升序
                list.sort(Comparator.comparing(AppletShopVo::getDistance));
            }
        }catch (Exception e){
            log.error(e.getMessage());
        }
        return list;
    }

    /**
     * 附近门店
     * @param cityId
     * @param longitude
     * @param latitude
     * @param spaceType
     * @param distance
     * @param pageNo
     * @param pageSize
     * @param shopName
     * @return
     */
    @GetMapping("/getSpaces")
    @ResponseBody
    public ReturnVO getSpaces(@RequestParam(value = "cityId",required = false) String cityId,
                              @RequestParam(value = "longitude",required = false) Double longitude,
                              @RequestParam(value = "latitude",required = false) Double latitude,
                              @RequestParam(value = "spaceType",required = false) String spaceType,
                              @RequestParam(value = "distance",required = false) Double distance,
                              @RequestParam(value = "pageNo",required = false) Integer pageNo,
                              @RequestParam(value = "pageSize",required = false) Integer pageSize,
                              @RequestParam(value = "shopName",required = false) String shopName){
        ReturnVO returnVO = new ReturnVO();
        List<AppletShopVo> list = new ArrayList<>();
        //总数据数
        int total = 0;
        //有数据 无是0
        int existence = 1;
        try {
            //获得当前城市所有的数据
            QueryWrapper<AppletShopVo> queryWrapper = new QueryWrapper<>();
            if (cityId != null && !"".equals(cityId)){
                queryWrapper.eq("cityId",cityId);
            }
            if (spaceType != null && !"".equals(spaceType)){
                queryWrapper.eq("spaceType",spaceType);
            }
            if (shopName != null && !"".equals(shopName)){
                queryWrapper.like("shopName",shopName);
            }
            if (appletShopService.count(queryWrapper) > 0){
                list = appletShopService.getShopView(queryWrapper,new Page<>(1,99999));
                Iterator<AppletShopVo> it =list.iterator();
                while (it.hasNext())
                {
                    AppletShopVo shop = it.next();
                    //计算两点间的距离
                    if (longitude !=null && latitude != null &&shop.getLongitude() != null && shop.getLatitude() != null){
                        Double distance1 = LatLonUtil.getDistance(longitude,latitude,shop.getLongitude(),shop.getLatitude());
                        //根据距离判断是否在指定范围
                        shop.setDistance(distance1/1000); //转换成公里
                        if (distance != null && distance != 0){
                            if(distance < distance1){ //移除指定范围外的数据
                                it.remove();
                            }
                        }
                    }else {
                        it.remove();
                    }
                }
            }
            //总记录数
            total = list.size();
            if (total > 0){ //存在
                if(startPage(list,pageNo,pageSize) != null){
                    list = startPage(list,pageNo,pageSize);
                }
            }else { //不存在
                //获得当前城市所有的数据
                QueryWrapper<AppletShopVo> cityWrapper = new QueryWrapper<>();
                if (cityId != null && !"".equals(cityId)){
                    cityWrapper.eq("cityId",cityId);
                }
                if (spaceType != null && !"".equals(spaceType)){
                    cityWrapper.eq("spaceType",spaceType);
                }
                if (shopName != null && !"".equals(shopName)){
                    cityWrapper.like("shopName",shopName);
                }
                total = appletShopService.count(cityWrapper);
                if (total > 0){
                    list = appletShopService.getShopView(cityWrapper,new Page<>(pageNo,pageSize));
                }
                existence = 0;
            }
            if (list.size() > 0){
                for (AppletShopVo shop:list){
                    //拼接图片网络路径
                    if (shop.getImageUrl() != null && !shop.getImageUrl().equals("")){
                        shop.setImageUrl(WebConfig.host+"images/"+shop.getImageUrl());
                    }
                    //计算两点间的距离
                    if (longitude !=null && latitude != null &&shop.getLongitude() != null && shop.getLatitude() != null){
                        Double distance1 = LatLonUtil.getDistance(longitude,latitude,shop.getLongitude(),shop.getLatitude());
                        shop.setDistance(distance1/1000); //转换成公里
                    }
                }
                //根据距离排序，距离升序
                list.sort(Comparator.comparing(AppletShopVo::getDistance));
            }
        }catch (Exception e){
            log.error(e.getMessage());
        }
        returnVO.setTotal(total);
        returnVO.setData(list);
        returnVO.setExistence(existence);
        return returnVO;
    }

    /**
     * 2.	地图找店
     * 2)	点击地图上门店图标呈现该门店信息
     * @param id 门店id
     * @return
     */
    @GetMapping("/getSpaceBaseInfo")
    @ResponseBody
    public AppletShopVo getSpaceBaseInfo(@RequestParam(value = "id",required = false) Integer id){
        AppletShopVo shop = new AppletShopVo();
        List<AppletShopVo> list = new ArrayList<>();
        try {
            //根据id查询到门店信息
            if (id != null){
                QueryWrapper<AppletShopVo> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("shopId",id);
                list = appletShopService.getShopView(queryWrapper,new Page<>(1,1));
            }
            if (list.size() > 0){
                shop = list.get(0);
                if (shop.getImageUrl() != null && !shop.getImageUrl().equals("")){
                    shop.setImageUrl(WebConfig.host+"images/"+shop.getImageUrl());
                }
                //根据商铺id查询空间信息
                QueryWrapper<AppletRoomVo> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("shopId",shop.getShopId());
                List<AppletRoomVo> appletRoomVoList = appletRoomService.getRoomView(queryWrapper,new Page<>(1,99999));
                if (appletRoomVoList.size() > 0){
                    for (AppletRoomVo roomVo:appletRoomVoList){
                        System.out.println(roomVo);
                        if (roomVo.getImageUrl() != null && !roomVo.getImageUrl().equals("")){
                            roomVo.setImageUrl(WebConfig.host+"images/"+roomVo.getImageUrl());
                        }
                    }
                }
                shop.setRoomVoList(appletRoomVoList);
            }

        }catch (Exception e){
            log.error(e.getMessage());
        }
        return shop;
    }

    /**
     *  4.	点击门店呈现门店详情
     * @param id 商铺id
     * @return
     */
    @GetMapping("/getSpaceInfo")
    @ResponseBody
    public AppletShopVo getSpaceInfo(@RequestParam(value = "id",required = false) Integer id,
                                     @RequestParam(value = "longitude",required = false) Double longitude,
                                     @RequestParam(value = "latitude",required = false) Double latitude){
        AppletShopVo shop = new AppletShopVo();
        List<AppletShopVo> list = new ArrayList<>();
        try {
            //根据id查询到门店信息
            if (id != null){
                QueryWrapper<AppletShopVo> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("shopId",id);
                list = appletShopService.getShopView(queryWrapper,new Page<>(1,1));
            }
            if (list.size() > 0){
                shop = list.get(0);
                if (shop.getImageUrl() != null && !shop.getImageUrl().equals("")){
                    shop.setImageUrl(WebConfig.host+"images/"+shop.getImageUrl());
                }
                //根据商铺id查询空间信息
                QueryWrapper<AppletRoomVo> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("shopId",shop.getShopId());
                List<AppletRoomVo> appletRoomVoList = appletRoomService.getRoomView(queryWrapper,new Page<>(1,99999));
                if (appletRoomVoList.size() > 0){
                    for (AppletRoomVo roomVo:appletRoomVoList){
                        if (roomVo.getImageUrl() != null && !roomVo.getImageUrl().equals("")){
                            roomVo.setImageUrl(WebConfig.host+"images/"+roomVo.getImageUrl());
                        }
                    }
                }
                shop.setRoomVoList(appletRoomVoList);
                //根据商铺id查询到商铺轮播图
                QueryWrapper<Images> imagesQueryWrapper = new QueryWrapper<>();
                imagesQueryWrapper.eq("Pid",shop.getShopId());
                imagesQueryWrapper.eq("Type",1);
                imagesQueryWrapper.orderByDesc("listorder");
                List<Images> imagesList = imagesService.list(imagesQueryWrapper);
                if (imagesList.size() > 0){
                    for (Images images:imagesList){
                        if (images.getUrl() != null && !images.getUrl().equals("")){
                            images.setUrl(WebConfig.host+"images/"+images.getUrl());
                        }
                    }
                }
                shop.setImagesList(imagesList);
            }
            if (longitude !=null && latitude != null && shop.getLongitude() != null && shop.getLatitude() != null){
                Double distance = LatLonUtil.getDistance(longitude,latitude,shop.getLongitude(),shop.getLatitude());
                //根据距离判断是否在指定范围
                shop.setDistance(distance/1000); //转换成公里
            }
        }catch (Exception e){
            log.error(e.getMessage());
        }
        return shop;
    }

    /**
     * 点击收藏
     */
    @PostMapping("/addCollection")
    @ResponseBody
    public ReturnVO addCollection(@RequestBody Collection collection,HttpServletRequest request){
        if (collection.getOpenid() == null || collection.getOpenid().equals("")){
            if (request.getSession().getAttribute("openid") != null){
                collection.setOpenid(request.getSession().getAttribute("openid").toString());
            }
        }
        try {
            collection.setCreateTime(new Date());
            collectionService.save(collection);
            return new ReturnVO();
        }catch (Exception e){
            log.error(e.getMessage());
            return new ReturnVO(ReturnCode.FAIL);
        }
    }

    /**
     * 收藏列表
     * @param openid 微信ID
     * @return
     */
    @GetMapping("/getCollections")
    @ResponseBody
    public ReturnVO getCollections(@RequestParam(value = "openid",required = false) String openid,
                                   @RequestParam(value = "userId",required = false) Integer userId,HttpServletRequest request){
        if (openid == null || openid.equals("")){
            if (request.getSession().getAttribute("openid") != null){
                openid = request.getSession().getAttribute("openid").toString();
            }
        }
        if (openid == null || openid.equals("")){
            return null;
        }
        ReturnVO returnVO = new ReturnVO();
        QueryWrapper<CollectionVo> queryWrapper = new QueryWrapper();
        if (openid != null){
            queryWrapper.eq("openid",openid);
        }
        if (userId != null){
            queryWrapper.eq("userId",userId);
        }
        List<CollectionVo> datalist = collectionService.search(queryWrapper,new Page<CollectionVo>(1,99999));
        if (datalist.size() > 0){
            for (CollectionVo collectionVo:datalist){
                //拼接图片网络路径
                if (collectionVo.getImageUrl() != null && !collectionVo.getImageUrl().equals("")){
                    collectionVo.setImageUrl(WebConfig.host+"images/"+collectionVo.getImageUrl());
                }
            }
        }
        returnVO.setData(datalist);
        return returnVO;
    }

    /**
     * 点击取消收藏
     * @param collectionID
     * @return
     */
    @GetMapping("/delCollection")
    @ResponseBody
    public ReturnVO delCollection(@RequestParam(value = "collectionID",required = false) Integer collectionID,
                                  @RequestParam(value = "openid",required = false) String openid,HttpServletRequest request){
        if (openid == null || openid.equals("")){
            openid = request.getSession().getAttribute("openid").toString();
        }
        try {
            if(collectionID != null){
                QueryWrapper<Collection> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("collectionID",collectionID);
                queryWrapper.eq("openid",openid);
                collectionService.remove(queryWrapper);
            }
            return new ReturnVO();
        }catch (Exception e){
            log.error(e.getMessage());
            return new ReturnVO(ReturnCode.FAIL);
        }
    }

    public String getCode(){
        long random1 = System.currentTimeMillis();
        Random random2 = new Random();
        int rd = random2.nextInt(9);
        String dateKey =  random1 + "" + rd;
        return dateKey;
    }

    /**
     * 获得首页轮播图
     * @return
     */
    @GetMapping("/getRotationChart")
    @ResponseBody
    public ReturnVO getRotationChart(){
        ReturnVO returnVO = new ReturnVO();
        QueryWrapper<Rotation> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("Status",1)
                    .eq("Type",1)
                    .orderByDesc("Sort");
        List<Rotation> list = rotationService.list(queryWrapper);
        if (list.size() > 0){
            //拼接图片网络路径
            List<String> urls = new ArrayList<>();
            for (Rotation rotation:list){
                if (rotation.getUrl() != null && !rotation.getUrl().equals("")){
                    rotation.setUrl(WebConfig.host+"images/"+rotation.getUrl());
                }
                urls.add(rotation.getUrl());
            }
            returnVO.setData(urls);
        }
        return returnVO;
    }

    /**
     * 获得轮播图
     * @return
     */
    @GetMapping("/getSpaceRotationChart")
    @ResponseBody
    public ReturnVO getSpaceRotationChart(){
        ReturnVO returnVO = new ReturnVO();
        QueryWrapper<Rotation> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("Status",1)
                .eq("Type",0)
                .orderByDesc("Sort");
        List<Rotation> list = rotationService.list(queryWrapper);
        if (list.size() > 0){
            //拼接图片网络路径
            List<String> urls = new ArrayList<>();
            for (Rotation rotation:list){
                if (rotation.getUrl() != null && !rotation.getUrl().equals("")){
                    rotation.setUrl(WebConfig.host+"images/"+rotation.getUrl());
                }
                urls.add(rotation.getUrl());
            }
            returnVO.setData(urls);
        }
        return returnVO;
    }

    /**
     * 跳转到商品展示页面
     * @return
     */
    @GetMapping("/shop")
    public String shop(String code,HttpServletRequest request,Integer id,//售货柜编号
                       HttpServletResponse response, ModelMap model) throws IOException {

        /*log.info("getOpenId: 售货柜列表页");
        if (id != null)
            this.cId = id;
        log.info("商品展示页面");
        String redirect_uri = WebConfig.redirect_uri; //需要配置 《网页授权获取用户基本信息》的回调地址

//-----在这里判断code是否已经存在于缓存中，如果存在，说明code已经使用过，需要重新获取code------
        List list = (List) request.getSession().getAttribute("openid_list");
        if (StringUtils.isNotBlank(code) && list != null && list.contains(code)) {
            //用过了
            code = "";
        }
        log.info("商品展示页面code："+code);
        //获取code
        if (StringUtils.isBlank(code)) {
            try {
                PrintWriter out = response.getWriter();
                out.println("<script>window.location.href='" + getCodeUrl(redirect_uri) + "'</script>");
                out.flush();
                out.close();
            } catch (IOException e) {
                log.error(e.getMessage());
            }
            return null;
        }
        String[] s = getOpenId(code);
        log.info("商品展示页面s："+Arrays.toString(s));
        String openId = s[0];
        String accessToken = s[1];
        System.out.println("手机登录openId=================================>" + openId);
        log.info("手机登录openId=================================>" + openId);

        //将openId发给页面
        this.openid = openId;*/
        return "commodity/test";
    }

    /**
     * 获取用户授权 得到openId,accessToken
     *
     * @param code
     * @return
     */
    public String[] getOpenId(String code) {
        log.info("getOpenId: 欢迎你");
        log.info("getOpenId:"+code);
        String tokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?grant_type=authorization_code";
        tokenUrl = tokenUrl + "&appid=" + WebConfig.appid + "&secret=" + WebConfig.secret + "&code=" + code;
        JSONObject json = null;
        try {
            HttpClientResult httpClientResult= HttpClientUtils.doGet(tokenUrl);
            String content=httpClientResult.getContent();
            json= JSONArray.parseObject(content);
            //------------在这里把使用过的code存入到缓存中--------

        } catch (JSONException e2) {
            log.error("----e2"+e2.getMessage());
        } catch (Exception e) {
            log.error("----e"+e.getMessage());
        }
        String openId = "";
        String accessToken = "";
        String[] s = new String[2];
        if (json != null) {
            try {
                openId = json.getString("openid");
                accessToken = json.getString("access_token");
                s[0] = openId;
                s[1] = accessToken;
            } catch (JSONException e) {
                String errcode = null;
                try {
                    errcode = json.getString("errcode");
                    log.error("errcode================>手机登录 获取用户授权失败" + errcode);
                } catch (JSONException e1) {
                    log.error(e1.getMessage());
                }
            }
        }
        return s;
    }
    /**
     * 获取code请求地址
     *
     * @param redirect_uri  回调地址  这个回调地址需要在微信公众号后台也进行配置 不然会显示"redirect_uri域名还是与后台配置不一致"
     * @param
     * @return
     */
    public String getCodeUrl(String redirect_uri) {
        redirect_uri= URLEncoder.encode(redirect_uri);   //使用 urlEncode 对链接进行处理
        String codeUrl = "https://open.weixin.qq.com/connect/oauth2/authorize";
        codeUrl = codeUrl + "?appid=" + WebConfig.appid + "&redirect_uri=" + redirect_uri
                + "&response_type=code&scope=snsapi_userinfo&state=jetcms#wechat_redirect";

        return codeUrl;
    }

    /**
     * 获得商品列表
     * @return
     */
    @PostMapping("/shop_show")
    @ResponseBody
    public ReturnVO shop_show(){
        log.info("getOpenId: 售货柜列表显示");
        ReturnVO returnVO = new ReturnVO();
        try {
            QueryWrapper<Cabinetitem> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("cabId",this.cId);
            List<Cabinetitem> list = cabinetitemService.list(queryWrapper);
            if (list.size() > 0){
                for (Cabinetitem cabinetitem:list){
                    if (cabinetitem.getImage() != null && !cabinetitem.getImage().equals("")){
                        cabinetitem.setImage(WebConfig.host+"images/"+cabinetitem.getImage());
                    }
                }
            }
            returnVO.setData(list);
        }catch (Exception e){
            log.error(e.getMessage());
            returnVO = new ReturnVO(ReturnCode.FAIL);
        }
        return returnVO;
    }

    private String createSign(Map<String,Object> map, String mchKey) {
        String tosstr = "appId="+map.get("appId")+"&nonceStr="+map.get("nonceStr")+"&package="+map.get("package")
                +"&signType=MD5&timeStamp="+map.get("timeStamp")+"&key=" + mchKey;
        return DigestUtils.md5Hex(tosstr).toUpperCase();
    }

    /**
     * 小程序 开门码
     */
    @GetMapping("/openCode")
    @ResponseBody
    public List<Object>  openCode(@RequestParam(value = "openId",required = false) String openId,
                                  @RequestParam(value = "openid",required = false) String openid,
                                  @RequestParam(value = "userId",required = false) String userId, HttpServletRequest request){
        log.info("开门码openid大写----"+openId);
        log.info("开门码openid小写----"+openid);
        List<Object> data=new ArrayList<>();
        try {

            Date beginDate = CalendarDate.addDate(new Date(), "min", 30);
            if(openId==null || openId.equals(""))
            {
                //那从user表获取openid
                HttpSession session = request.getSession();
                if(session.getAttribute("openid")!=null)
                    openId=session.getAttribute("openid").toString();
            }
            //查询这个微信的预约 openId
            QueryWrapper<Appointment> wrapper=new QueryWrapper<>();
            wrapper.eq("WeChat",openId);
            wrapper.eq("state",1);
            //  wrapper.lt("StartTime",beginDate);
            wrapper.gt("EndTime",new Date());
            List<Appointment> list=appointmentService.list(wrapper);
            if(list.size()==0) return data;
            Date nowdate=new Date();
            for (Appointment dataitem:list) {
                Date begin=dataitem.getStartTime();
                Date end=dataitem.getEndTime();
                // if (DateTime.Now >= begin.AddMinutes(-15) && DateTime.Now <= end && !string.IsNullOrEmpty(aid.ToString()))
                //if(nowdate.after(CalendarDate.addDate(begin,"min",-30)) && nowdate.before(end))
             if(nowdate.before(end))
                {
                    //说明有预约
                    //获取所有房间信息
                    Room roomdata=roomService.getById(dataitem.getRoomId());
                    Shop shopdata=shopService.getById(roomdata.getShopId());
                    //result="AB|"+formattime.format(dataitem.getStartTime())+"|"+formattime.format(dataitem.getEndTime())+"|"+dataitem.getRoomId()+"|"+dataitem.getId()+"|"+openId;
                    String result="AB|"+formattime.format(dataitem.getStartTime())+"|"+formattime.format(dataitem.getEndTime())+"|"+dataitem.getRoomId()+"|"+dataitem.getId();

                    //获取所有房间信息
                    Map<String,String> map=new HashMap<>();
                    map.put("shopName",shopdata.getName());
                    map.put("shopAddress",shopdata.getAddress());
                    map.put("roomName",roomdata.getName());
                    map.put("appointDate",formatdata.format(dataitem.getAppointDate()));
                    map.put("beginTime",dataitem.getStartInt().toString().substring(0,2)+":"+dataitem.getStartInt().toString().substring(2,4));
                    map.put("endTime",dataitem.getEndInt().toString().substring(0,2)+":"+dataitem.getEndInt().toString().substring(2,4));

                    map.put("code",result);
                    data.add(map);
                }
            }

        }catch (Exception e){
            log.error(e.getMessage());
        }

        return data;
    }

    /**
     * 申请加盟
     * @param joinIn
     * @return
     */
    @PostMapping("/joinIn")
    @ResponseBody
    public ReturnVO joinIn(@RequestBody JoinIn joinIn){
        ReturnVO returnVO = new ReturnVO();
        try {
            joinIn.setCreateTime(new Date());
            joinInService.save(joinIn);
        }catch (Exception e){
            log.error(e.getMessage());
            returnVO = new ReturnVO(ReturnCode.FAIL);
        }
        return returnVO;
    }

    /**
     * 关于我们
     * @return
     */
    @GetMapping("/about")
    @ResponseBody
    public ReturnVO show(){
        ReturnVO returnVO = new ReturnVO();
        try {
            AboutUs aboutUs = aboutUsService.getById(1);
            returnVO.setData(aboutUs);
        }catch (Exception e){
            log.error(e.getMessage());
            returnVO = new ReturnVO(ReturnCode.FAIL);
        }
        return returnVO;
    }

    /**
     * 常见问题
     * @return
     */
    @GetMapping("/faq")
    @ResponseBody
    public ReturnVO faq(){
        ReturnVO returnVO = new ReturnVO();
        try {
            List<CommonProblem> list = commonProblemService.list();
            returnVO.setData(list);
        }catch (Exception e){
            log.error(e.getMessage());
            returnVO = new ReturnVO(ReturnCode.FAIL);
        }
        return returnVO;
    }

    /**
     * 我的推广
     * @param userId
     * @return
     */
    @GetMapping("/getPromotionCode")
    @ResponseBody
    public Map<String,Object> getPromotionCode(@RequestParam(value = "userId",required = false) String userId,HttpServletRequest request){
        /**
         * 推广码相关属性  promoted已推广，successful成功推广，profit收益，record推广记录
         */
        Map<String,Object> map = new HashMap<>();
        int promoted = 0;
        int successful = 0;
        Double profit = 0.0;
        /**
         * 推广记录  avatarUrl头像，nickName昵称，createDateTime时间
         */
        List<Map<String,Object>> record = new ArrayList<>();

        try {
            //已推广
            QueryWrapper<Users> promotedWrap = new QueryWrapper();
            promotedWrap.eq("memberId",userId);
            promoted = userService.count(promotedWrap);
            //成功推广
            QueryWrapper<Users> successfulWrap = new QueryWrapper();
            successfulWrap.eq("memberId",userId);
            successfulWrap.eq("types",1); //是会员
            successfulWrap.eq("userType",5); //是会员
            successful = userService.count(successfulWrap);
            //收益
            QueryWrapper<ChargingFlow> profitWrap = new QueryWrapper();
            profitWrap.select("IFNULL(sum(money),0) as profit ");
            profitWrap.eq("userId",userId);
            Map<String,Object> map1 = chargingFlowService.getMap(profitWrap);
            profit = Double.valueOf(String.valueOf(map1.get("profit")));
            //推广记录
            QueryWrapper<Users> recordWrap = new QueryWrapper();
            recordWrap.eq("memberId",userId);
            List<Users> list = userService.list(recordWrap);
            if (list.size() > 0){
                for (Users users:list){
                    Map<String,Object> map2 = new HashMap<>();
                    map2.put("avatarUrl",users.getAvatarUrl());
                    map2.put("nickName",users.getNickName());
                    map2.put("createDateTime",users.getCreateDateTime());
                    record.add(map2);
                }
            }
            map.put("promoted",promoted);
            map.put("successful",successful);
            map.put("profit",profit);
            map.put("record",record);
        }catch (Exception e){
            log.error(e.getMessage());
        }

        return map;
    }

    /**
     * 信息维护
     * @return
     */
    @GetMapping("/maintain")
    @ResponseBody
    public ReturnVO maintain(@RequestParam(value = "userId",required = false) Integer userId,
                             @RequestParam(value = "phone",required = false) String phone){
        ReturnVO returnVO = new ReturnVO();
        try {
            Users users = new Users();
            users.setUserID(userId);
            users.setPhone(phone);
            userService.updateById(users);
        }catch (Exception e){
            log.error(e.getMessage());
            returnVO = new ReturnVO(ReturnCode.FAIL);
        }
        return returnVO;
    }

    /**
     * 返回shop和room的信息，用于续单
     * @param shopId
     * @param roomId
     */
    @GetMapping("/getRenewal")
    @ResponseBody
    public Map<String,Object> getRenewal(@RequestParam(value = "shopId",required = false) Integer shopId,
                           @RequestParam(value = "roomId",required = false) Integer roomId){
        Map<String,Object> map = new HashMap<>();
        //空间信息
        AppletShopVo appletShopVo = null;
        //房间信息
        AppletRoomVo appletRoomVo = null;
        QueryWrapper<AppletShopVo> shopVoQueryWrapper = new QueryWrapper<>();
        shopVoQueryWrapper.eq("shopId",shopId);
        List<AppletShopVo> appletShopVoList = appletShopService.getShopView(shopVoQueryWrapper,new Page<>(1,1));
        if (appletShopVoList.size() > 0){
            appletShopVo = appletShopVoList.get(0);

        }
        QueryWrapper<AppletRoomVo> roomVoQueryWrapper = new QueryWrapper<>();
        roomVoQueryWrapper.eq("roomId",roomId);
        List<AppletRoomVo> appletRoomVoList = appletRoomService.getRoomView(roomVoQueryWrapper,new Page<>(1,1));
        if (appletRoomVoList.size() > 0){
            appletRoomVo = appletRoomVoList.get(0);
        }

        //拼接图片路径
        if (appletShopVo != null){
            //根据商铺id查询到商铺轮播图
            QueryWrapper<Images> imagesQueryWrapper = new QueryWrapper<>();
            imagesQueryWrapper.eq("Pid",appletShopVo.getShopId());
            imagesQueryWrapper.eq("Type",1);
            imagesQueryWrapper.orderByDesc("listorder");
            List<Images> imagesList = imagesService.list(imagesQueryWrapper);
            if (imagesList.size() > 0){
                for (Images images:imagesList){
                    if (images.getUrl() != null && !images.getUrl().equals("")){
                        images.setUrl(WebConfig.host+"images/"+images.getUrl());
                    }
                }
            }
            appletShopVo.setImagesList(imagesList);
            if (appletShopVo.getImageUrl() != null && !appletShopVo.getImageUrl().equals("")){
                appletShopVo.setImageUrl(WebConfig.host+"images/"+appletShopVo.getImageUrl());
            }
        }
        if (appletRoomVo != null){
            if (appletRoomVo.getImageUrl() != null && !appletRoomVo.getImageUrl().equals("")){
                appletRoomVo.setImageUrl(WebConfig.host+"images/"+appletRoomVo.getImageUrl());
            }
        }
        map.put("shop",appletShopVo);
        map.put("room",appletRoomVo);
        return map;
    }

    /**
     * 对list进行分页
     * @param list 需要分页的数据
     * @param pageNo 页码
     * @param pageSize 每页多少条数据
     * @return
     */
    public List<AppletShopVo> startPage(List<AppletShopVo> list, Integer pageNo, Integer pageSize) {
        List<AppletShopVo> appletShopVoList = new ArrayList<>();
        if (list == null) {
            return appletShopVoList;
        }
        if (list.size() == 0) {
            return appletShopVoList;
        }

        int count = list.size(); // 记录总数
        int pageCount = 0; // 页数
        if (count % pageSize == 0) {
            pageCount = count / pageSize;
        } else {
            pageCount = count / pageSize + 1;
        }

        int fromIndex = 0; // 开始索引
        int toIndex = 0; // 结束索引

        if (pageNo < pageCount) {
            fromIndex = (pageNo - 1) * pageSize;
            toIndex = fromIndex + pageSize;
        } else {
            fromIndex = (pageNo - 1) * pageSize;
            toIndex = count;
        }

        return list.subList(fromIndex, toIndex);
    }

//    /**
//     * 将百度经纬度转换成腾讯经纬度
//     * @param lat
//     * @param lng
//     * @return
//     */
//    public Map<String,Double> Convert_BD09_To_GCJ02(double lat, double lng) {
//        Map<String,Double> map = new HashMap<>();
//        double x_pi = Math. PI * 3000.0 / 180.0;
//        double x = lng - 0.0065, y = lat - 0.006;
//        double z = Math. sqrt(x * x + y * y) - 0.00002 * Math.sin(y * x_pi);
//        double theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * x_pi);
//        lng = z * Math. cos(theta );
//        lat = z * Math. sin(theta );
//        map.put("lng",lng);
//        map.put("lat",lat);
//        return map;
//    }


}
